package com.zxl.yunpicture.domain.space.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxl.yunpicture.domain.space.entity.SpaceUser;
import com.zxl.yunpicture.domain.space.repository.SpaceUserRepository;
import com.zxl.yunpicture.domain.space.service.SpaceUserDomainService;
import com.zxl.yunpicture.infrastructure.common.DeleteRequest;
import com.zxl.yunpicture.infrastructure.exception.ErrorCode;
import com.zxl.yunpicture.infrastructure.exception.ThrowUtils;
import com.zxl.yunpicture.interfaces.dto.spaceuser.SpaceUserQueryRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author ZhangXL
* @description 针对表【space_user(空间用户关联)】的数据库操作Service实现
* @createDate 2025-03-04 22:06:30
*/
@Service
public class SpaceUserDomainServiceImpl implements SpaceUserDomainService {


    @Resource
    private SpaceUserRepository spaceUserRepository;

    @Override
    public QueryWrapper<SpaceUser> getQueryWrapper(SpaceUserQueryRequest spaceUserQueryRequest) {
        QueryWrapper<SpaceUser> queryWrapper = new QueryWrapper<>();
        if (spaceUserQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = spaceUserQueryRequest.getId();
        Long spaceId = spaceUserQueryRequest.getSpaceId();
        Long userId = spaceUserQueryRequest.getUserId();
        String spaceRole = spaceUserQueryRequest.getSpaceRole();
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceRole), "spaceRole", spaceRole);
        return queryWrapper;
    }


    @Override
    public void deleteSpaceUser(DeleteRequest deleteRequest) {
        Long id = deleteRequest.getId();
        // 判断是否存在
        SpaceUser oldSpaceUser = spaceUserRepository.getById(id);
        ThrowUtils.throwIf(oldSpaceUser == null, ErrorCode.NOT_FOUND_ERROR);
        boolean exists = spaceUserRepository.lambdaQuery().
                eq(SpaceUser::getUserId, oldSpaceUser.getUserId()).
                eq(SpaceUser::getSpaceId, oldSpaceUser.getSpaceId()).
                exists();
        ThrowUtils.throwIf(!exists,ErrorCode.OPERATION_ERROR,"该用户不在该空间");
        // 操作数据库
        boolean result = spaceUserRepository.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }



}




